package com.zhenzhang.myblog.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhenzhang.myblog.utils.JsonResult;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object loginUser = request.getSession().getAttribute("loginUser");
        if(loginUser==null
                &&
                !(request.getRequestURI().equals("/api/user") && request.getMethod().equalsIgnoreCase("post"))
        ){
            JsonResult res = JsonResult.getInstance();
            res.setCode(403);
            res.setMessage("权限不足或登录失效");
            response.setStatus(403);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(res);
            return false;
        }
        return true;
    }
}
